#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

__author__ = "Yunpeng Li <ypli.chn@outlook.com.com>"
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from EU.info import news
from EU.info import region
from EU.info import comments
from EU.info import broadcast
from EU.info import spot
from EU.admin import auth
from EU.admin import UserForm
from EU.admin import action
from django import forms
from EU.feedback import feedback
from io import BytesIO
import json
import logging
from EU.admin.StatusCode import StatusCode
logger = logging.getLogger(__name__)

@csrf_exempt
def get_news_list(request):
    """
    处理获取新闻列表的请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get("device_id",None)
        start = request.POST.get("start",0)
        num = request.POST.get("num",4)
        result = news.get_news_list(start,num)
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

def get_news(request):
    """
    处理获取新闻的请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':

        id = request.POST.get('id',None)
        print("id%s", id)
        result=news.get_news(id)
        #result={"content":temp_news.content,"tilte":temp_news.title,'author':temp_news.author,'date':temp_news.date}
        #content=[{'is_table':False,'content':temp_news.content}]
        return HttpResponse(json.dumps(result), content_type="application/json")
    else:
        result = 'Request must be a POST'
    return HttpResponse(json.dumps(result), content_type="application/json")


@csrf_exempt
def update_news(request):
    result = None
    if request.method == 'POST':
        if check_admin(request):
            id=request.POST.get("id")
            date=request.POST.get("date",None)
            title=request.POST.get("title",None)
            author=request.POST.get("author",None,)
            content=request.POST.get("content",None)
            result=action.update_news(id,date,title,author,content)
        else:
            result = result = json.dumps({
                "status":StatusCode.IllegalUser,
                "message":"非法用户"
            })
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

@csrf_exempt
def delete_news(request):
    result = None
    if request.method == 'POST':
        if check_admin(request):
            id=request.POST.get("id",None)
            result = action.delete_news(id)
        else:
            result = result = json.dumps({
                "status":StatusCode.IllegalUser,
                "message":"非法用户"
            })

    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")


@csrf_exempt
def get_region(request):
    """
    处理获取景区信息的请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get('device_id',None)
        result = region.get_region()
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

@csrf_exempt
def get_weather(request):
    """
    处理获取天气信息的请求
    :param requst:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get('device_id',None)
        result = region.get_weather()
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

@csrf_exempt
def get_spot_type_list(request):
    """
    处理获取景点类型的请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get('device_id',None)
        result = spot.get_spot_type_list()
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

@csrf_exempt
def update_spot_type(request):
    """
    处理更新景点类型的请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        if check_admin(request):
            spot_id = request.POST.get('id',None)
            is_open = request.POST.get('is_open',False)
            result = action.update_spot_type(spot_id,is_open)
        else:
            result = result = json.dumps({
                "status":StatusCode.IllegalUser,
                "message":"非法用户"
            })
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

@csrf_exempt
def get_spot_list(request):
    """
    处理获取景点列表的请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get('device_id')
        type = request.POST.get('type',1) # 默认为景点
        start = request.POST.get('start',0)
        num = request.POST.get('num',10)
        result = spot.get_spot_list(type,start,num)
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

@csrf_exempt
def get_all_spot(request):
    """
    获取所有类型
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get('device_id')
        result = spot.get_all_spot()
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

@csrf_exempt
def search_spot(request):
    """
    处理搜索景点的请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get('device_id')
        key = request.POST.get('key')
        result = spot.search_spot(key)
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")
    pass

@csrf_exempt
def get_spot(request):
    """
    处理获取景点信息的请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get('device_id')
        spot_id = request.POST.get('id')
        result = spot.get_spot(spot_id)
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

@csrf_exempt
def get_broadcast(request):
    """
    处理获取广播的请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get('device_id')
        result = broadcast.get_broadcast(device_id)
    else:
        result = 'Request must be a POST'

    return HttpResponse(result, content_type="application/json")


def get_all_broadcast(request):
    """
    获取所有广播
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        timestamp = request.POST.get('timestamp')
        result = broadcast.get_all_broadcast()
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")


def delete_broadcast(request):
    """
    删除一条广播
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        if check_admin(request):
            broadcast_id = request.POST.get('id')
            result = action.delete_broadcast(broadcast_id)
        else:
            result = result = json.dumps({
                "status":StatusCode.IllegalUser,
                "message":"非法用户"
            })
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

def post_broadcast(request):
    """
    发布一条广播
    :param requst:
    :return:
    """
    result = None
    if request.method == 'POST':
        if check_admin(request) :
            message = request.POST.get('message')
            print("获取消息:%s" % message)
            time_length = request.POST.get('time_length',60*2) #默认2分钟
            id = 1 # 这里从session获取
            result = action.post_broadcast(id,message,time_length)
        else:
            result = result = json.dumps({
                "status":StatusCode.IllegalUser,
                "message":"非法用户"
            })
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")


@csrf_exempt
def login(request):
    """
    处理登录请求
    :param request:
    :return:
    """
    if request.method == 'POST':
        username = request.POST.get('username')

        password = request.POST.get('password')
        code = request.POST.get('code',".")
        correct_code = request.session.get('CheckCode',default=None)
        result = auth.admin_login(username,password,code,correct_code)
        print(result['status'])
        if result["status"] == StatusCode.Success:
            request.session['user'] = username
    else:
        result = 'Request must be a POST'
    return HttpResponse(json.dumps(result), content_type="application/json")


@csrf_exempt
def update_password(request):
    """
    处理更新密码的请求
    :param request:
    :return:
    """
    if request.method == 'POST':
        if check_admin(request):
            username = request.session.get('user')
            old_password = request.POST.get('old_password')
            new_password = request.POST.get('new_password')
            confirm_password = request.POST.get('confirm_password')
            result = auth.admin_update_password(username,old_password,new_password,confirm_password)
        else:
            result = result = json.dumps({
                "status":StatusCode.IllegalUser,
                "message":"非法用户"
            })
    else:
        result = 'Request must be a POST'
    return HttpResponse(json.dumps(result), content_type="application/json")

def check_code(request):
    """
    处理获取验证码的请求
    :param request:
    :return:
    """
    (validate_code,stream) = auth.get_check_code()
    logger.info("获取验证码: %s" % validate_code)
    logger.error('Something went wrong!')
    request.session['CheckCode'] = validate_code
    return HttpResponse(stream,'jpeg')

def update_spot(request):
    if request.method == 'POST':
        uf = UserForm.UserForm(request.POST,request.FILES)
        print(uf)
        if uf.is_valid():
            uf1=uf.clean()
            print(uf1)
            name = uf.cleaned_data['name']
            score = uf.cleaned_data['score']
            image=uf.cleaned_data['picture']
            introduction = uf.cleaned_data['introduction']
            longitude = uf.cleaned_data['longitude']
            latitude = uf.cleaned_data['latitude']
            voice=uf.cleaned_data['voice']
            id = uf.cleaned_data['id']
            type=uf.cleaned_data['type_id']
            if(id==0):
                id=111111111111111
            result = action.update_spot(id,name,type,longitude,latitude,image,score,introduction,voice)
            return HttpResponse(json.dumps(result), content_type="application/json")
        else:
            result={}
            result['status'] = StatusCode.UnknowError
            result['message'] = "表单格式错误"
            return HttpResponse(json.dumps(result), content_type="application/json")

def post_news(request):
    result = None
    if request.method == 'POST':

        if check_admin(request):
            date=request.POST.get("date")
            title = request.POST.get("title")
            author = request.POST.get("author")
            content = request.POST.get('content')
            result = action.post_news(date,title,author,content)

        else:
            result = json.dumps({
                "status":StatusCode.IllegalUser,
                "message":"非法用户"
            })
    else:
        result = 'Request must be a POST'
    return HttpResponse(result)



# --------------------------- 反馈模块 --------------------------------

def post_complaints(request):
    """
    处理获取投诉请求
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        device_id = request.POST.get('device_id')
        message = request.POST.get('message')
        name = request.POST.get('name','游客')
        phone = request.POST.get('phone')
        mail = request.POST.get('mail')
        result = feedback.post_complaints(device_id,message,name,phone,mail)
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")


def get_complaints(request):
    """
    获取所有投诉
    :param request:
    :return:
    """
    result = None
    if request.method == 'POST':
        if check_admin(request):
            timestamp = request.POST.get('timestamp')
            result = feedback.get_complaints(timestamp)
        else:
            result = json.dumps({
                "status":StatusCode.IllegalUser,
                "message":"非法用户"
            })
    else:
        result = 'Request must be a POST'
    return HttpResponse(result, content_type="application/json")

def check_admin(request):
    """
    检查权限
    :return:
    """
    username = request.session.get('user')

    return auth.check_admin(username)
